//
//  LeftView.m
//  Daybook
//
//  Created by liutaifeng on 16/5/23.
//  Copyright © 2016年 zhangbin. All rights reserved.
//

#import "LeftView.h"
#import <BmobSDK/Bmob.h>
#import "UIButton+WebCache.h"

@interface LeftView ()
<
 UICollectionViewDataSource,
 UICollectionViewDelegate
>
@property (nonatomic, strong) UIButton *headLoginButton;
@property (nonatomic, strong) UIButton *userNameButton;
@property (nonatomic, strong) UIButton *twoCodeButton;
@property (nonatomic, strong) LeftButton *syncButton;
@property (nonatomic, strong) LeftButton *addButton;

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, assign) NSInteger mark;

;


@property (nonatomic, strong) UIButton *editButton;
@end

@implementation LeftView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self createView];
    }
    return self;
}
- (void)setModelArray:(NSMutableArray *)modelArray {
    if (_modelArray != modelArray) {
        _modelArray = modelArray;
        [_collectionView reloadData];
    }
}


- (void)createView {
    
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];
//    self.backgroundColor = [UIColor lightGrayColor];
    
       [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(headChanged:) name:@"headChanged" object:nil];
       [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(headClear:) name:@"headClear" object:nil];
    
    self.headLoginButton = ({
        UIButton *tempButton = [UIButton buttonWithType:UIButtonTypeCustom];
        tempButton.frame = CGRectMake(25 / 414.0 * MAIN_WIDTH, (MAIN_HEIGHT * (35 / 736.0)), 70 / 414.0 * MAIN_WIDTH, 70 / 414.0 * MAIN_WIDTH);
        [self addSubview:tempButton];
        [tempButton setImage:[UIImage imageNamed:@"headUnlogin.png"] forState:UIControlStateNormal];
        [tempButton addTarget:self action:@selector(headLoginButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        tempButton.backgroundColor = [UIColor lightGrayColor];
        tempButton.layer.borderWidth = 1;
        tempButton.layer.cornerRadius = (70 / 414.0 * MAIN_WIDTH) / 2.0;
        tempButton.layer.masksToBounds = YES;
        tempButton.layer.borderColor = [[UIColor whiteColor]CGColor];
        tempButton;
    });
    
    self.userNameButton = ({
        UIButton *tempButton = [UIButton buttonWithType:UIButtonTypeCustom];
        tempButton.frame = CGRectMake(95 / 414.0 * MAIN_WIDTH, (MAIN_HEIGHT * (60 / 736.0)), 160 / 414.0 * MAIN_WIDTH, 20 / 414.0 * MAIN_WIDTH);
        [self addSubview:tempButton];
        [tempButton setTitle:@"点击登录" forState:UIControlStateNormal];
        [tempButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        tempButton.titleLabel.textAlignment = NSTextAlignmentLeft;
//        tempButton.backgroundColor = [UIColor blackColor];
        [tempButton addTarget:self action:@selector(headLoginButtonAction:) forControlEvents:UIControlEventTouchUpInside];
//        tempButton.backgroundColor = [UIColor lightGrayColor];
        tempButton;
    });
    
    BmobUser *bUser = [BmobUser getCurrentUser];
    if (bUser) {
        //进行操作
        BmobFile *file = (BmobFile *)[bUser objectForKey:@"image"];
        [self.headLoginButton sd_setImageWithURL:[NSURL URLWithString:file.url] forState:UIControlStateNormal];
        [self.userNameButton setTitle:bUser.username forState:UIControlStateNormal];
    }else{
        //对象为空时，可打开用户注册界面
    }
    
    self.twoCodeButton = ({
        UIButton *tempButton = [UIButton buttonWithType:UIButtonTypeCustom];
        tempButton.frame = CGRectMake(240 / 414.0 * MAIN_WIDTH, (MAIN_HEIGHT * (49 / 736.0)), 40 / 414.0 * MAIN_WIDTH, 40 / 414.0 * MAIN_WIDTH);
        //        [self addSubview:tempButton];
        [tempButton setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        [tempButton addTarget:self action:@selector(twoCodeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        tempButton.backgroundColor = [UIColor lightGrayColor];
        tempButton;
    });
    
    self.syncButton = ({
        LeftButton *tempButton = [LeftButton buttonWithType:UIButtonTypeCustom];
        tempButton.frame = CGRectMake(0, (MAIN_HEIGHT * (130 / 736.0)), 160 / 414.0 * MAIN_WIDTH, 40 / 414.0 * MAIN_WIDTH);
        [self addSubview:tempButton];
        [tempButton setTitle:@"同步" forState:UIControlStateNormal];
        [tempButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [tempButton setImage:[UIImage imageNamed:@"mingxi.png"] forState:UIControlStateNormal];
        tempButton.titleLabel.font = [UIFont systemFontOfSize:17 / 414.0 * MAIN_WIDTH];
        [tempButton addTarget:self action:@selector(syncButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        tempButton.layer.borderWidth = 1;
        tempButton.layer.borderColor = [[UIColor colorWithWhite:0.5 alpha:0.2]CGColor];
        tempButton.adjustsImageWhenHighlighted = NO;
        tempButton.backgroundColor = [UIColor darkGrayColor];
        tempButton;
    });
    self.addButton = ({
        LeftButton *tempButton = [LeftButton buttonWithType:UIButtonTypeCustom];
        tempButton.frame = CGRectMake(159 / 414.0 * MAIN_WIDTH, (MAIN_HEIGHT * (130 / 736.0)), 160 / 414.0 * MAIN_WIDTH, 40 / 414.0 * MAIN_WIDTH);
        [self addSubview:tempButton];
        [tempButton setTitle:@"添加" forState:UIControlStateNormal];
        tempButton.titleLabel.font = [UIFont systemFontOfSize:17 / 414.0 * MAIN_WIDTH];
        [tempButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [tempButton setImage:[UIImage imageNamed:@"addH_32.png"] forState:UIControlStateNormal];
        [tempButton addTarget:self action:@selector(addButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        //tempButton.backgroundColor = [UIColor blackColor];
        tempButton.layer.borderWidth = 1;
        tempButton.layer.borderColor = [[UIColor colorWithWhite:0.5 alpha:0.2]CGColor];
        tempButton.adjustsImageWhenHighlighted = NO;
        tempButton.backgroundColor = [UIColor darkGrayColor];
        
        tempButton;
    });
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(120 / 414.0 * MAIN_WIDTH, self.frame.size.height / 5);
    layout.sectionInset = UIEdgeInsetsMake(25 / 414.0 * MAIN_WIDTH, 25 / 414.0 * MAIN_WIDTH, 25 / 414.0 * MAIN_WIDTH, 25 / 414.0 * MAIN_WIDTH);
    layout.minimumInteritemSpacing = 20 / 414.0 * MAIN_WIDTH;
    layout.minimumLineSpacing = 20 / 414.0 * MAIN_WIDTH;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 170 /736.0 * MAIN_HEIGHT, 320 / 414.0 * MAIN_WIDTH, MAIN_HEIGHT - 170 / 736.0 * MAIN_HEIGHT) collectionViewLayout:layout];
    [self addSubview:_collectionView];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    
    [_collectionView registerClass:[LeftCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([LeftCollectionViewCell class])];
    
    self.editButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _editButton.frame = CGRectMake(10 / 414.0 * MAIN_WIDTH, MAIN_HEIGHT - 90 / 736.0 * MAIN_HEIGHT, 40 / 414.0 * MAIN_WIDTH, 40 / 414.0 * MAIN_WIDTH);
    [self addSubview:_editButton];
    _editButton.layer.cornerRadius = 40 / 414.0 * MAIN_WIDTH / 2;
    _editButton.backgroundColor = [UIColor whiteColor];
    _editButton.alpha = 0.5;
    [_editButton setImage:[UIImage imageNamed:@"bianjiLightGray_64.png"] forState:UIControlStateNormal];
    [_editButton addTarget:self action:@selector(editButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    // 背景
    _collectionView.backgroundColor = [UIColor clearColor];
//    _collectionView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];

}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _modelArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    LeftCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([LeftCollectionViewCell class]) forIndexPath:indexPath];
    cell.model = self.modelArray[indexPath.row];

    cell.deleteButton.tag = 1000 + indexPath.row;
    [cell.deleteButton addTarget:self action:@selector(deleteButton:) forControlEvents:UIControlEventTouchUpInside];
    cell.setButton.tag = 2000 + indexPath.row;
    [cell.setButton addTarget:self action:@selector(setButton:) forControlEvents:UIControlEventTouchUpInside];
    if (self.isEdit == NO) {
        cell.bottomView.hidden = YES;
        cell.markImageView.hidden = NO;
        if (_index == indexPath.row) {
            cell.markImageView.hidden = NO;
        }
        else {
            cell.markImageView.hidden = YES;
        }

    }
    else {
        cell.bottomView.hidden = NO;
        cell.markImageView.hidden = YES;
    }
        return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (_isEdit == NO) {
        AccountBookModel *model = _modelArray[indexPath.row];
        [self.delegate exchangeBackground:model.accountBookBackground name:model.accountBookName];
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        [user setInteger:indexPath.row forKey:@"index"];
        
//        NSLog(@"%ld", [user integerForKey:@"index"]);
        _index = indexPath.row;
        [_collectionView reloadData];
        
        [self getAccountName];
    }
}

- (void)getAccountName {
    NSArray *totalAccountArr = [[AccountBookSQL shareDataBaseTool] select];
    AccountBookModel *model = totalAccountArr[_index];

    
    NSUserDefaults *accountBookIndex = [NSUserDefaults standardUserDefaults];
    [accountBookIndex setValue:[NSString stringWithFormat:@"%ld", _index] forKey:@"accountBookIndex"];
    
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"rightViewExchangeAccountBook" object:[NSString stringWithFormat:@"%ld", _index]];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"exchangeAccountBook" object:[NSString stringWithFormat:@"%ld", _index]];

    
    NSLog(@"当前的账本名称: %@", model.accountBookName);
    NSLog(@"当前的账本下标: %ld", _index);
}

- (void)deleteButton:(UIButton *)button {
    self.mark = button.tag - 1000;
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"确认删除" message:nil delegate:self cancelButtonTitle:@"确认" otherButtonTitles:@"取消", nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        if (_mark == [user integerForKey:@"index"]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"当前账本正在使用, 无法删除" message:nil delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
            [alert show];
        }
        else {
            [[AccountBookSQL shareDataBaseTool] deleteCollect:self.modelArray[_mark]];
            [self.modelArray removeObjectAtIndex:_mark];
            if (_mark < [user integerForKey:@"index"]) {
                [user setInteger:[user integerForKey:@"index"] - 1 forKey:@"index"];
                _index = [user integerForKey:@"index"];
            }
            [_collectionView reloadData];
            if (_modelArray.count == 0) {
                self.isEdit = NO;
            }
            NSLog(@"删除下标为: %ld", _mark);
#pragma mark - 删除账本
            [RealmTool deleteDayBookInRealmFromIndex:[NSString stringWithFormat:@"%ld", _mark]];
        }
        
    }
}


- (void)setButton:(UIButton *)button {
    self.isEdit = NO;
    [self.collectionView reloadData];
    NSInteger index = button.tag - 2000;
    [self.delegate setModel:(AccountBookModel *)_modelArray[index] index:index];
    
}


- (void)editButtonAction:(UIButton *)button {
    self.isEdit = !self.isEdit;
    [_collectionView reloadData];
}
- (void)headLoginButtonAction:(UIButton *)button {
    self.isEdit = NO;
    [self.collectionView reloadData];
    [self.delegate headLoginAction];
}

- (void)twoCodeButtonAction:(UIButton *)button {
    [self.delegate twoCodeAction];
}

- (void)syncButtonAction:(UIButton *)button {
    [self.delegate syncAction];
}

- (void)addButtonAction:(UIButton *)button {
    self.isEdit = NO;
    [self.collectionView reloadData];
    [self.delegate addAction];
}

- (void)headChanged:(NSNotification *)notification {
    
    
    [self.headLoginButton setImage:notification.object forState:UIControlStateNormal];
    
    BmobUser *bUser = [BmobUser getCurrentUser];
    if (bUser) {
        //进行操作
        [self.userNameButton setTitle:bUser.username forState:UIControlStateNormal];
    }else{
        //对象为空时，可打开用户注册界面
    }
    
}

- (void)headClear:(NSNotification *)notification {
    
    [self.userNameButton setTitle:@"点击登录" forState:UIControlStateNormal];
    
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
